package com.jty.module_user.viewmodel

import androidx.lifecycle.MutableLiveData
import com.arialyy.aria.core.Aria
import com.czl.lib_base.config.AppConstants
import com.jty.lib_base.base.BaseBean
import com.jty.lib_base.base.BaseViewModel
import com.jty.lib_base.base.MyApplication
import com.jty.lib_base.bus.event.SingleLiveEvent
import com.jty.lib_base.data.DataRepository
import com.jty.lib_base.data.bean.UserInfoBean
import com.jty.lib_base.event.LiveBusCenter
import com.jty.lib_base.extension.ApiSubscriptHelper
import com.jty.lib_base.route.RouteCenter
import com.jty.lib_base.utils.MultiClickUtil
import com.jty.lib_base.utils.RxThreadHelper
import com.orhanobut.logger.Logger


/**
 * author: zhouyh
 * created on: 2021/9/14 11:08 上午
 * description: 登录模块viewModel
 */
class UserViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    var userInfoBean = MutableLiveData<UserInfoBean>(model.getUserInfoData())

    val uc = UIChangeEvent()

    /**
     * UI刷新事件 用于观察者
     */
    class UIChangeEvent{
        val clickToF: SingleLiveEvent<Int> = SingleLiveEvent()
        val refreshUserInfoEvent : SingleLiveEvent<UserInfoBean> = SingleLiveEvent()
    }


    override fun onStart() {
        super.onStart()
        tvTitle.set("我的")
        btnBackVisibility.set(false)
        getUserInfo()
    }

    override fun onResume() {
        super.onResume()
        var userInfo = model.getUserInfoData()
        userInfoBean.value?.let {
            if(it.mobile != userInfo?.mobile) {
                it.mobile = userInfo?.mobile?:it.mobile
                userInfoBean.postValue(userInfoBean.value)
            }
            if (it.avatarUrl!=userInfo?.avatarUrl){
                userInfoBean.postValue(userInfo)
            }
        }
    }

    fun clickToF(type:Int) {
        if(!MultiClickUtil.isFastClick()) {
            return
        }
        Logger.i("点击了：${type}")
        uc.clickToF.postValue(type)
        when(type) {
            -1 -> startContainerActivity(AppConstants.Router.User.F_DATA)
            2 -> startContainerActivity(AppConstants.Router.User.F_MYPEN)
            3 -> startContainerActivity(AppConstants.Router.User.F_SET)
        }
    }

    fun getUserInfo(){
        model.getUserInfo()
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriptHelper<BaseBean<UserInfoBean>>() {
                override fun onResult(t: BaseBean<UserInfoBean>) {
                    dismissLoading()
                    if (t.code == 0){
                        t.data?.let {
                            model.saveUserInfoData(it)
                            uc.refreshUserInfoEvent.postValue(it)
                        }
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                }
            })
    }

}